import os
import random
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from api_key.model import ApiKey
from api_key import get_api_key_by_key
import sha


def generate_api_key(name, email):
    sh = sha.new()
    sh.update(str(name))
    sh.update(str(email))
    sh.update('%s' % random.random())
    return sh.hexdigest()
def generate_secret_key(name, email):
    sh = sha.new()
    sh.update(str(name))
    sh.update(str(email))
    sh.update(generate_api_key(name,email))
    sh.update('%s' % random.random())
    return sh.hexdigest()

class ListApiKey(webapp.RequestHandler):
    def get(self):
        apis = ApiKey.all().fetch()

        template_values = {
            'apis' : apis
        }

        path = os.path.join(os.path.dirname(__file__), 'list.html')
        self.response.out.write(template.render(path, template_values))

class AddApiKey(webapp.RequestHandler):
    def get(self):
        key = self.request.get('added')
        # TODO api = find api_key where __key__ = key
        api = get_api_key_by_key(key)

        template_values = {
            'api' : api
        }

        path = os.path.join(os.path.dirname(__file__), 'add.html')
        self.response.out.write(template.render(path, template_values))

    def post(self):
        api = ApiKey()
        api.name = self.request.get('api_name').decode('utf-8')
        api.email = self.request.get('api_email').decode('utf-8')
        api.enabled = True if self.request.get('api_enabled') == 'on' else False
        api.api_key = generate_api_key(api.name, api.email)
        api.secret_key = generate_secret_key(api.name, api.email)
        api.put()

        self.redirect('/api_key/add?added=%s' % api.key(), True)